import './index.scss'
import request from '@/utils/request'


const NAME = 'listQuery';

export default {
    name: NAME,
    formCreateParser: {
        mergeProp(ctx) {
            const props = ctx.prop.props;
            if (!props.nodeKey) props.nodeKey = 'id';
            if (!props.props) props.props = {
                label: 'title'
            };
        }
    },
    props: {
        formCreateInject: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            loading: false,
            defaultAttars: { // 按钮默认配置
                type: 'text',
                size: 'small'
            },
            tableHeight: 200,
            tableList: [],
            tableColumn: [],
            tableBtnWidth: 200,
            listQuery: {
                page:1,
                limit:20,
                pageSizes:[20]
            }, // table 分页配置
            total: 0, // table 总记录数
            formInline:{},
            paramSubmit:{}, // 保存提交的参数，刷新用
            // excel
            excelFilename:'excel报表',
            excelDataList:[],
            excelTotal:0,
            excelRate:'',
            excelPageLimit:100,
            loadingText:'loading'
        }
    },
    mounted(){

        this.$nextTick(()=> {
            // 浏览器、元素大小变化时，动态调整table高度
            const tableHeight = this.formCreateInject.prop.props.tableHeight
            const reduceHeight = this.formCreateInject.prop.props.reduceHeight
            if (tableHeight) {
                this.tableHeight = tableHeight
            }
            if (reduceHeight) {
                const clientHeight = `${document.documentElement.clientHeight}`;//获取浏览器可视区域高度
                this.tableHeight = clientHeight - reduceHeight
            }
        })



        //
        const isLoadDataAuto = this.formCreateInject.prop.props.isLoadDataAuto
        if (isLoadDataAuto) {
            this.loadData({})
        }
    },
    methods: {
        handleClick(e, row, click, post) { // 表单按钮点击
            const fApi = this.formCreateInject.api
            e && e.stopPropagation && e.stopPropagation()
            if (post){
                let url = post.url
                let newParam = {}
                Object.assign(newParam, row, post.data)
                // url query里参数，存入store中，所有api调用时，一起发给后端，参数中有token, 可用作身份验证
                if (this.$route&&this.$route.query&&this.$route.query.dynamicFormId) {
                    let queryData = {}
                    Object.assign(queryData, this.$route.query)
                    Object.assign(newParam, {'urlQueryData':queryData})
                }
                // api
                return request({
                    url,
                    method:'post',
                    data:newParam
                }).then(r => {
                    console.log(r)
                    if (!r.success) {
                        this.notify(r)
                        return;
                    }
                    this.refresh()
                })
            }else{
                click && click(fApi, row)
            }
        },
        handleSizeChange(size) { // 分页一页显示条数改变回调
            this.listQuery.limit = size
        },
        handleCurrentChange(page) { // 分页当前页数改变回调
            this.listQuery.page = page
            const fApi = this.formCreateInject.api
            const formData = fApi.formData();
            formData.pageStart=(page-1)*this.listQuery.limit
            formData.pageLimit=this.listQuery.limit
            this.loadData(formData)
        },
        indexMethod(index) { // 序号格式化
            const { page, limit } = this.listQuery
            return (page - 1) * limit + index + 1
        },

        query() {
            this.listQuery.page = 1
            console.log(this.listQuery)
            const fApi = this.formCreateInject.api
            const formData = fApi.formData();
            formData.pageStart=0
            formData.pageLimit=this.listQuery.limit
            this.loadData(formData)
        },
        loadData(formData){
            console.log('loadData.formData from comp v2')
            console.log(formData)
            this.loading = true
            // param
            let url = this.formCreateInject.prop.props.url
            url=url?url.trim():''
            let method = this.formCreateInject.prop.props.method
            method=method?method.trim():''
            let paramData = this.formCreateInject.prop.props.paramData
            const newParam = {}
            Object.assign(newParam, paramData, formData)
            // url query里参数，存入store中，所有api调用时，一起发给后端，参数中有token, 可用作身份验证
            if (this.$route&&this.$route.query&&this.$route.query.dynamicFormId) {
                let queryData = {}
                Object.assign(queryData, this.$route.query)
                Object.assign(newParam, {'urlQueryData':queryData})
            }
            // api
            return request({
                url,
                method,
                data: newParam
            }).then(r => {
                console.log(r)
                if (!r.success) {
                    this.notify(r)
                    this.loading = false
                    return;
                }
                const data = r.obj
                const total = r.map.total
                this.formCreateInject.prop.props.data = data
                this.formCreateInject.prop.props.total = total
                // 保存参数
                this.paramSubmit = {}
                Object.assign(this.paramSubmit, newParam)
                this.loading = false
            })
        },

        async refresh() {
            await this.loadData(this.paramSubmit)
        },

        export() {
            console.log('export...')
            const fApi = this.formCreateInject.api
            const formData = fApi.formData();
            formData.pageStart=0
            formData.pageLimit=this.excelPageLimit
            // param
            let url = this.formCreateInject.prop.props.url
            url=url?url.trim():''
            let method = this.formCreateInject.prop.props.method
            method=method?method.trim():''
            let paramData = this.formCreateInject.prop.props.paramData
            const newParam = {}
            Object.assign(newParam, paramData, formData)
            // url query里参数，存入store中，所有api调用时，一起发给后端，参数中有token, 可用作身份验证
            if (this.$route&&this.$route.query&&this.$route.query.dynamicFormId) {
                let queryData = {}
                Object.assign(queryData, this.$route.query)
                Object.assign(newParam, {'urlQueryData':queryData})
            }
            // 查询, 调用生成Excel
            this.downloadLoading = true
            this.excelDataList = []
            this.fetchExcelList(url, method, newParam)
        },
        fetchExcelList(url, method, params) {
            this.loading = true
            request({
                url,
                method,
                data: params
            }).then(result => {
                if (!result.success) {
                    this.notify(result)
                    this.loading = false
                    return
                }
                console.log(result)
                // 分批查询，做进度条
                result.obj.forEach(item=>{
                    this.excelDataList.push(item)
                })
                this.excelTotal = result.map.total

                let rate = (params.pageStart+1)/this.excelTotal
                if (rate>1)rate=1
                console.log('----- page ---- ')
                console.log(params.pageStart+1)
                console.log(this.excelTotal)
                console.log(rate)
                this.excelRate = parseInt(rate*100) + '%'
                this.loadingText = this.excelRate
                console.log(this.excelRate)
                //check is continue
                if (rate<1) {
                    params.pageStart = params.pageStart + this.excelPageLimit
                    this.fetchExcelList(url, method, params)
                }else{
                    // 生成Excel
                    this.makeExcel()
                }
            })
        },
        // 生成Excel
        makeExcel() {
            //excel 列
            let properties = []
            let labels = []
            this.tableColumn.map(item => {
                if (item.type !== 'button') {
                    properties.push(item.prop)
                    labels.push(item.label)
                }
            })
            import('@/excel/excelexport').then(excel => {
                const tHeader = labels //[ '名称', '创建时间', '创建人']  // excel中显示的列名
                const filterVal = properties //[ 'merchantName', 'createdate', 'createman'] // excel中显示哪些列，与tHeader对应
                const list = this.excelDataList
                const data = this.formatJson(filterVal, list)

                //excel 支持多sheet
                let filename = this.excelFilename
                let titleList = [] //['垃圾分类评分', '垃圾分类评分明细']
                let headerList = [tHeader]
                let dataList = [data]
                let sheetNames = ['sheet1']
                let autoWidth = true
                excel.export2Excel(titleList,headerList,dataList,filename,sheetNames, autoWidth)

                this.excelRate = ''
                this.downloadLoading = false
            })
            this.loading = false
        },
        // 处理数据类型
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else if(j.indexOf('.')!= -1){
                    let obj = j.split('.')[0]
                    let objProperty = j.split('.')[1]
                    return this.$options.filters['getJsonName'](v[obj],objProperty)
                } else {
                    return v[j]
                }
            }))
        },

        createSlotScope(list) {
            return {
                scopedSlots: {
                    default: scope => {
                        return list.map(btn => {
                            if (btn.confirm) {
                                return (
                                    <el-popconfirm class='pop-confirm' title={btn.confirm} { ...{ on: { onConfirm: (e) => this.handleClick(e, scope.row, btn.click, btn.post) }} }>
                                        <el-button
                                            slot='reference'
                                            class={{ 'gray': btn.isGray }}
                                            {...{ props: { ...this.defaultAttars, ...btn.attrs }}}
                                            {...btn.otherAttrs}
                                        >
                                            { btn.name }
                                        </el-button>
                                    </el-popconfirm>
                                )
                            }
                            return (
                                <el-button
                                    class={{ 'gray': btn.isGray }}
                                    {...{ on: { click: (e) => this.handleClick(e, scope.row, btn.click, btn.post) }}}
                                    {...{ props: { ...this.defaultAttars, ...btn.attrs }}}
                                    {...btn.otherAttrs}
                                >
                                    {btn.name}
                                </el-button>
                            )
                        })
                    }
                }
            }
        },

    },
    render(h) {
        const { tableList, listQuery, total, handleSizeChange, handleCurrentChange } = this
        this.tableList = this.formCreateInject.prop.props.data
        this.total = this.formCreateInject.prop.props.total
        this.tableColumn = this.formCreateInject.prop.props.header

        return (
            <div>
                <el-table {...this.formCreateInject.prop} height={this.tableHeight} style={{'width':'100%'}}
                          stripe
                          border
                          fit
                          highlight-current-row
                          v-loading={this.loading}
                          element-loading-text={this.loadingText}
                >
                    <el-table-column
                        type='index'
                        label='序号'
                        min-width={100}
                        index={this.indexMethod}
                    />
                    {
                        this.tableColumn.map(item => {
                            if (item.type === 'button') {
                                return (
                                    <el-table-column label={item.label || '操作'} width={this.tableBtnWidth}
                                                     {...this.createSlotScope(item.list)}
                                    >
                                    </el-table-column>
                                )
                            }
                            else {
                                return (
                                    <el-table-column
                                        key={item.key}
                                        type={item.type}
                                        prop={item.prop}
                                        label={item.label}
                                        width={item.width}
                                        min-width={item.minWidth}
                                        {...{
                                            scopedSlots: {
                                                default: scope => {
                                                    return item.render ? item.render(h, scope) : scope.row[item.prop]
                                                }
                                            }
                                        }}
                                    />
                                )
                            }
                        })
                    }
                </el-table>

                {
                    (listQuery && tableList && tableList.length) ? (
                        <el-pagination
                            class='pagination'
                            style={{'margin-top':'20px !important'}}
                            background
                            current-page={listQuery.page}
                            //page-sizes={listQuery.pageSizes || [10, 20, 30, 40]}
                            page-sizes={listQuery.pageSizes}
                            page-size={listQuery.limit}
                            layout='prev, pager, next, sizes, jumper, total'
                            total={total}
                            onSize-change={handleSizeChange}
                            onCurrent-change={handleCurrentChange}
                        />
                    ) : null
                }
            </div>
        )
    }
}
